# coding=utf-8
import base64
import functools
import hashlib
import time
import types
from flask import jsonify, request, redirect
from app.MySession import MySession
from . import redis
import requests, json

CODE_SUCCESS = 200
CODE_ERROR = 500
CODE_LOGIN = 301
CODE_EMPTY = 400
CODE_FAIL = 401
CODE_EXIST = 402  # 手机号码已被注册
CODE_BREAK = 403  # 参数不正确
PAGE_NUM = 12

LOGIN_KEY = "login"


# 获取IP
def get_current_ip():
    ip = request.headers.get('X-Real-Ip', request.remote_addr)
    return ip


# 转化成json格式
def to_counts_json(response, counts):
    response_json = jsonify(response)
    response_json.headers['Access-Control-Allow-Origin'] = '*'
    response_json.headers['counts'] = counts
    return response_json


# 转化成json格式
def to_json(response):
    response_json = jsonify(response)
    response_json.headers['Access-Control-Allow-Origin'] = '*'
    return response_json


# md5加密
def md5(string):
    if isinstance(string, types.StringType):
        m = hashlib.md5()
        m.update(string)
        return m.hexdigest()
    else:
        return ''


# 时间戳转换为日期（年月日时分秒）
def int_day(timestamp):
    dd = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
    return dd


#  时间戳转换为日期（年月日）
def int_ymd(timestamp):
    day = time.strftime('%Y-%m-%d', time.localtime(timestamp))
    return day


# 日期转换为时间戳
def day_int(day):
    dt = int(time.mktime(time.strptime(day, '%Y-%m-%d')))
    return dt


# 返回当月的第一天跟最后一天
def getMonthFirstDayAndLastDay(year=None, month=None):
    """
    :param year: 年份，默认是本年，可传int或str类型
    :param month: 月份，默认是本月，可传int或str类型
    :return: firstDay: 当月的第一天，datetime.date类型
              lastDay: 当月的最后一天，datetime.date类型
    """
    import datetime, calendar
    if year:
        year = int(year)
    else:
        year = datetime.date.today().year
    if month:
        month = int(month)
    else:
        month = datetime.date.today().month
    # 获取当月第一天的星期和当月的总天数
    firstDayWeekDay, monthRange = calendar.monthrange(year, month)
    # 获取当月的第一天
    firstDay = datetime.date(year=year, month=month, day=1)
    lastDay = datetime.date(year=year, month=month, day=monthRange)
    return firstDay, lastDay


# 后台登录验证
def admin_login(func):
    @functools.wraps(func)
    def request_session(*args, **kwargs):
        session = request.cookies.get("uid")
        if session is None or not MySession.reactive(session):
            return redirect('/admin/login.html')
        else:
            uid = MySession.get_name(session)
        return func(*args, **kwargs)

    return request_session


# 登录验证
def verify_login(func):
    @functools.wraps(func)
    def request_session(*args, **kwargs):
        session = request.values.get("session")
        if session is None or not MySession.reactive(session):
            data = {
                'code': CODE_LOGIN
            }
            return to_json(data)
        else:
            uid = MySession.get_name(session)
        return func(uid, *args, **kwargs)

    return request_session


# 极光短信验证码
def jg_send_sms(phone_num, temp_id):
    appkey = '197357efe46fbc322f9b0bbf'
    master = '1e3a2571d7760b9bc02ab6e7'
    url_str = appkey + ':' + master
    base_str = base64.b64encode(url_str)
    ds = "Basic "
    ds = ds + base_str
    url = 'https://api.sms.jpush.cn/v1/codes'
    data = {
        'mobile': phone_num,
        'temp_id': temp_id
    }
    headers = {
        "Authorization": ds
    }
    r = requests.post(url, data=json.dumps(data), headers=headers, verify=False, timeout=10)
    s = r.text
    d = json.loads(s)
    code_str = 'msg_id'
    if code_str in d.keys():
        p_str = 'msg' + str(phone_num)
        redis.set(p_str, d['msg_id'], ex=300)
        code = CODE_SUCCESS
    else:
        code = CODE_ERROR
    return code


# 极光短信验证码验证
def verify_code(phone_num, code_num):
    p_str = 'msg' + str(phone_num)
    msg_id = redis.get(p_str)
    if msg_id is None:
        msg_id = ''
    url = 'https://api.sms.jpush.cn/v1/codes/' + str(msg_id) + '/valid'
    appkey = '197357efe46fbc322f9b0bbf'
    master = '1e3a2571d7760b9bc02ab6e7'
    url_str = appkey + ':' + master
    base_str = base64.b64encode(url_str)
    ds = "Basic "
    ds = ds + base_str
    data = {
        'code': code_num
    }
    headers = {
        "Authorization": ds
    }
    r = requests.post(url, data=json.dumps(data), verify=False, headers=headers, timeout=10)
    s = r.text
    d = json.loads(s)
    try:
        if d['is_valid']:
            return CODE_SUCCESS
        else:
            return CODE_ERROR
    except BaseException as e:
        print e
        return CODE_ERROR

